import Dialog from "../../miniprogram_npm/@vant/weapp/dialog/dialog"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressArr: null,
    show: false,
    checked: false
  },
  // 点击添加地址
  addAddress() {
    wx.navigateTo({
      url: '/pages/detailAddress/detailAddress?type=add',
    })
  },
  // 点击编辑
  edit(e) {
    // let index = e.detail;
    let index = e.currentTarget.dataset.key;
    wx.navigateTo({
      url: '/pages/detailAddress/detailAddress?key=' + index + '&addressArr=' + JSON.stringify(this.data.addressArr) + "&type=edit",
    })
  },
  // 点击删除
  deleteAddress(e) {
    Dialog.confirm({
      title: '温馨提示',
      message: '您确定要删除该地址吗',
    }).then(() => {
      // 确定
      let key = e.currentTarget.dataset.key;
      let list = wx.getStorageSync('setAddressInfoArr')
      let defaultAddress = wx.getStorageSync('defaultAddress')
      list.splice(key, 1)
      defaultAddress.splice(0, 1)

      this.setData({
        addressArr: list,
        show: true
      })
      setTimeout(() => {
        this.setData({
          show: false
        })
      }, 1000)
      wx.setStorageSync('setAddressInfoArr', list)
      wx.setStorageSync('defaultAddress', defaultAddress)
    }).catch(() => {
      // 取消
      // on cancel
    });
  },
  // 点击设为默认
  checkboxChange(e) {
    let index = e.currentTarget.dataset.key;
    let list = wx.getStorageSync('setAddressInfoArr')

    this.setData({
      checked: !this.data.checked
    })
    list[index].checked = this.data.checked;

    if (list[index].checked == true) {
      let defaultAddress = [];
      defaultAddress.push(list[index]);
      wx.setStorageSync('defaultAddress', defaultAddress)

      list.forEach(function (item) {
        item.checked = false;
      })
      list[index].checked = true;
      wx.setStorageSync('setAddressInfoArr', list)
    } else {
      list.forEach(function (item) {
        item.checked = false;
      })
      wx.setStorageSync('setAddressInfoArr', list)
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      addressArr: wx.getStorageSync('setAddressInfoArr')
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})